package com.android.love.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.love.R;
import com.android.love.adapter.CartAdapter;
import com.android.love.db.DatabaseUtil;
import com.android.love.util.ActivityUtil;
import com.android.love.util.LogUtil;
import com.android.love.view.BadgeView;
import com.android.love.vo.Goods;
import com.android.love.vo.MyRequest;
import com.android.love.vo.Order;
import com.android.love.vo.SingleGoods;
import com.github.kevinsawicki.wishlist.ViewFinder;

public class CartActivity extends BasePageActivity {
	private List<Goods> carts = Collections.emptyList();
	private ViewFinder cartFinder;
	private ListView myCartList;

	private CartAdapter cartAdapter;
	/** 迭代器 **/
	private Iterator<Goods> iterator;

	/** 是否有元素被选中 **/
	private boolean hasChecked = false;
	private CheckBox checkBox_total;
	private float total_price;
	private RelativeLayout rl_cart_item_top;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Goods good = null;
			int position = 0;
			if (carts.size() > 0) {
				position = msg.arg1;
				good = (Goods) carts.get(position);
			}
			switch (msg.what) {
			case CART_DELETE:
				for (Goods cart : carts) {
					cart.setChecked(true);
					total_price = cart.getPrice() * cart.getCount()
							+ total_price;
				}
				checkBox_total.setChecked(true);
				updateTotalPrice();
				updateBottomCart();

				List<Goods> lists = DatabaseUtil.getInstance(context)
						.queryCart();
				if (lists.size() == 0) {
					hide(rl_cart_item_top);
					hide(cartFinder.find(R.id.iv_shuaxin));
					// ActivityUtil.show(CartActivity.this, "购物车没有添加商品");
				}
				cartAdapter.notifyDataSetChanged();
				break;
			case CART_ADD:
				if (good.isChecked()) {
					total_price = total_price + good.getPrice();
				}
				updateTotalPrice();
				break;
			case CART_REDUCE:
				if (good.isChecked()) {
					total_price = total_price - good.getPrice();
				}
				updateTotalPrice();
				break;
			case CART_CHECK:
				if (good.isChecked()) {
					total_price = total_price + good.getPrice()
							* good.getCount();
				} else {
					total_price = total_price - good.getPrice()
							* good.getCount();
				}
				updateTotalPrice();
				// cartAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View cartView = inflater.inflate(R.layout.activity_cart, null);
		setContentView(cartView);
		cartFinder = new ViewFinder(cartView);
		process();
		setListener();
		getData();
	}

	@Override
	protected void onResume() {
		mApplication.setDefaultIndex(SHOPCAR);
		super.onResume();
		LogUtil.i(TAG, "onResume");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void process() {
		myCartList = cartFinder.find(R.id.lv_cart);
		rl_cart_item_top = cartFinder.find(R.id.rl_cart_item_top);
		hide(rl_cart_item_top);
		cartFinder.setDrawable(R.id.iv_shuaxin, R.drawable.btn_delete);
		cartFinder.setDrawable(R.id.iv_top_meinv, R.drawable.meinv);
		cartFinder.setText(R.id.top_title, "购物车");
		checkBox_total = cartFinder.find(R.id.checkBox_total);
		checkBox_total.setChecked(true);
		super.process();

	}

	@Override
	protected void getData() {
		super.getData();
		MyRequest req = new MyRequest();
		getDataFromTask(context, CART, req, req, false, true);
	}

	@Override
	protected void setListener() {
		super.setListener();
		cartFinder.find(R.id.iv_shuaxin).setOnClickListener(this);
		cartFinder.find(R.id.iv_jisuan).setOnClickListener(this);
		// myCartList.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// final CheckBox status = (CheckBox) view
		// .findViewById(R.id.checkBox);
		// Goods msg = (Goods) myCartList.getItemAtPosition(position);
		// if (msg.isChecked()) {
		// msg.setChecked(false);
		// status.setChecked(false);
		// total_price = total_price - msg.getPrice();
		// } else {
		// msg.setChecked(true);
		// status.setChecked(true);
		// total_price = total_price + msg.getPrice();
		// }
		// updateTotalPrice();
		// }
		// });
		checkBox_total
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							for (Goods msg : carts) {
								msg.setChecked(true);
								total_price = msg.getPrice() * msg.getCount()
										+ total_price;
							}
							updateTotalPrice();
						} else {
							for (Goods msg : carts) {
								msg.setChecked(false);
							}
							total_price = 0;
							updateTotalPrice();
						}
						cartAdapter.notifyDataSetChanged();

					}

				});
	}

	private void updateTotalPrice() {
		// cartFinder.setText(R.id.tv_total_price, "￥" + total_price);
		cartFinder.setText(R.id.tv_total_price,
				"￥" + (float) Math.round((float) (total_price * 100)) / 100);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_shuaxin:
			iterator = carts.iterator();
			while (iterator.hasNext()) {
				Goods msg = (Goods) iterator.next();
				if (msg.isChecked()) {
					hasChecked = true;
				}
			}
			if (!hasChecked) {
				Toast.makeText(context, "您没有选中任何购物项", 0).show();
				return;
			}
			hasChecked = false;
			// showDeleteDialog();
			newYesNoDialog(R.string.delete_title, R.string.delete_message,
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								final List<Goods> deleteList = new ArrayList<Goods>();
								new Thread() {
									public void run() {
										iterator = carts.iterator();
										while (iterator.hasNext()) {
											final Goods msg = (Goods) iterator
													.next();
											if (msg.isChecked()) {
												iterator.remove();
												deleteList.add(msg);
												total_price = total_price
														- msg.getPrice()
														* msg.getCount();
											}
										}
										DatabaseUtil.getInstance(context)
												.deleteFrovite(deleteList);
										handler.sendEmptyMessage(CART_DELETE);
									};
								}.start();
								break;
							// case DialogInterface.BUTTON_NEGATIVE:
							//
							// break;

							default:
								break;
							}

						}
					}).show();
			break;
		case R.id.iv_jisuan:
			iterator = carts.iterator();
			while (iterator.hasNext()) {
				Goods msg = (Goods) iterator.next();
				if (msg.isChecked()) {
					hasChecked = true;
				}
			}
			if (!hasChecked) {
				Toast.makeText(context, "您没有选中任何购物项", 0).show();
				return;
			}
			hasChecked = false;
			Intent intent = new Intent(context, OrderActivity.class);
			Order order = new Order();
			order.setSum(total_price);
			List<SingleGoods> sGoods = new ArrayList<SingleGoods>();
			for (int i = 0; i < carts.size(); i++) {
				if (carts.get(i).isChecked()) {
					SingleGoods goods = new SingleGoods();
					goods.setAttribute(carts.get(i).getColor().get(0) + " "
							+ carts.get(i).getSize().get(0) + " "
							+ carts.get(i).getFormat().get(0));
					goods.setCount(carts.get(i).getCount());
					goods.setPrice(carts.get(i).getPrice());
					goods.setGoods_id(carts.get(i).getGoods_id());
					goods.setGoods_image(carts.get(i).getGoods_image());
					goods.setGoods_name(carts.get(i).getGoods_name());
					sGoods.add(goods);
				}
			}
			order.setGoods(sGoods);
			intent.putExtra("order", order);
			// startActivity(intent);
			startActivityForResult(intent, TIJIAO);
			overridePendingTransition(R.anim.slide_up_in, R.anim.hold);
			break;

		default:
			break;
		}

	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		switch (tag) {
		case CART:
			if (object != null) {
				carts = (List<Goods>) object;
				if (carts.size() > 0) {
					show(rl_cart_item_top);
					if (cartAdapter == null) {
						for (Goods good : carts) {
							good.setChecked(true);
							total_price = good.getPrice() * good.getCount()
									+ total_price;
						}
						updateTotalPrice();
						cartAdapter = new CartAdapter(context, loader, carts,
								handler);
						myCartList.setAdapter(cartAdapter);
					} else {
						cartAdapter.notifyDataSetChanged();
					}
				} else {
					hide(rl_cart_item_top);
					hide(cartFinder.find(R.id.iv_shuaxin));
					ActivityUtil.show(CartActivity.this, "购物车没有添加商品");
				}
			} else {
				hide(rl_cart_item_top);
				hide(cartFinder.find(R.id.iv_shuaxin));
				ActivityUtil.show(CartActivity.this, "购物车没有添加商品");
			}

			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == TIJIAO) {
			if (arg2 != null) {
				boolean result = arg2.getBooleanExtra("result", false);
				if (result) {
					// 删除对应购物项
					final List<Goods> deleteList = new ArrayList<Goods>();
					new Thread() {
						public void run() {
							iterator = carts.iterator();
							while (iterator.hasNext()) {
								final Goods msg = (Goods) iterator.next();
								if (msg.isChecked()) {
									iterator.remove();
									deleteList.add(msg);
									total_price = total_price - msg.getPrice()
											* msg.getCount();
								}
							}
							DatabaseUtil.getInstance(context).deleteFrovite(
									deleteList);
							handler.sendEmptyMessage(CART_DELETE);
						};
					}.start();

					Order order = (Order) arg2.getSerializableExtra("order");
					Intent intent = new Intent(context, MyOrderDetail_1.class);
					intent.putExtra("order", order);
					intent.putExtra("show", true);
					startActivityForResult(intent, 0);
				}
			}
		}
	}
}
